package com.aim.controller;

import com.aim.common.base.BaseController;
import com.aim.common.exception.KaptchaException;
import com.aim.common.handler.log.LogManager;
import com.aim.common.handler.log.factory.LogTaskFactory;
import com.aim.common.util.KaptchaUtil;
import com.aim.common.util.SystemUtil;
import com.aim.common.util.WebUtil;
import com.aim.config.shiro.ShiroKit;
import com.aim.config.shiro.ShiroUser;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @AUTO 登陆控制器
 * @Author AIM
 * @DATE 2019/4/24
 */
@Controller
public class LoginController extends BaseController {

    private static String PREFIX = "login";

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = {"/login.html", "/login"}, method = RequestMethod.GET)
    public String login(Model model) {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + "/";
        } else {
            model.addAttribute("kaptchaOnOff", KaptchaUtil.getKaptchaOnOff());
            return PREFIX;
        }
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali(HttpServletRequest request) {
        String username = WebUtil.getPara("username").trim();
        String password = WebUtil.getPara("password").trim();
        String remember = WebUtil.getPara("remember");
        // 获取shiro中用户信息
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        //如果开启了记住我功能
        if ("on".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }

        if (KaptchaUtil.getKaptchaOnOff()) {
            String captcha = WebUtil.getPara("captcha").trim();
            // Session中获取验证码
            Object rightCode = WebUtil.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (!rightCode.equals(captcha)) {
                throw new KaptchaException("验证码错误");
            }
        }

        //执行shiro登录操作
        currentUser.login(token);

        //登录成功，记录登录日志
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        LogManager.me().execLog(LogTaskFactory.loginLog(shiroUser.getUserId(), SystemUtil.getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);

        return REDIRECT + "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        LogManager.me().execLog(LogTaskFactory.exitLog(ShiroKit.getUserNotNull().getUserId(), SystemUtil.getIp()));
        ShiroKit.getSubject().logout();
        Cookie[] cookies = WebUtil.getRequest().getCookies();
        int cookieCount = cookies.length;

        for (int i = 0; i < cookieCount; ++i) {
            Cookie cookie = cookies[i];
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            WebUtil.getResponse().addCookie(temp);
        }
        return REDIRECT + PREFIX;
    }

    /**
     * 跳转到session超时页面
     */
    @RequestMapping("/sessionError")
    public String error(Model model) {
        model.addAttribute("tips", "session超时");
        return PREFIX;
    }
}
